<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="角色名称">
      <el-input v-model="form.roleName" />
    </el-form-item>
    <el-form-item label="角色权限">
      <el-tree ref="treeRef" :data="menus" :props="treeProps" show-checkbox />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">新增角色</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>

</template>

<script>
import { routes } from '../../../router/index'
import { rolePost } from '../../../api/user'
export default {
  data() {
    return {
      form: {
        roleName: '',
      },
      menus: routes[0].children,
      treeProps: {
        label: (data, node) => {
          // console.log(data, node)
          return data.meta.label
        }
      }
    }
  },
  methods: {
    onSubmit() {
      let roleMenu = this.getCheckedTree()
      rolePost({ ...this.form, roleMenu }).then(res => {
        console.log(res)
        this.$emit('trans-role-data', { ...this.form, ObjectId })
      })
      // console.log(roleMenu)
    },
    getCheckedTree() {
      // console.log(this.$refs.treeRef.getCheckedNodes(true))
      let list = this.$refs.treeRef.getCheckedNodes(true)
      let tempList = []//存储父级
      let result = []//存储最终结果
      list.forEach(item => {
        const parent = this.menus.find(itm => {
          return itm.children?.some(children => {
            return children.meta.label == item.meta.label
          })
        })
        // console.log([parent.meta.label])
        //有父级
        if (parent) {
          if (!tempList.includes(parent.path)) {
            tempList.push(parent.path)
            result.push({
              path: parent.path,
              meta: parent.meta,
              children: [item]
            })
          } else {
            result.find(res => { return res.path == parent.path }).children.push(item)
          }
        } else {
          result.push(item)
        }
      });
      console.log(tempList)
      console.log(result)
      return result
    }
  }
}
</script>

<style lang="scss" scoped>

</style>